var addPage = avalon.define({
	$id: "page",
	uid: "",
	list:{
		couponImage:''
	},
	imgs:[],
	totalScore:0,
	quantity:1,
	dt:'',
	email:'',
	recipient:'',
	phoneNumber:'',
	address:'',
	provision:''
});

mui.ready(function() {
	var uid = $("#uid").val();
	addPage.uid = uid;
	// if("" != uid) {
	// 	mui.ajax('/customer/get.json', {
	// 		data: {
	// 			uid: addPage.uid
	// 		},
	// 		dataType: 'json',
	// 		success: function(data) {
	// 			if(""!=data&&null!=data){
	// 				addPage.email = data.email;
	// 			}
	// 		}
	// 	});
	// }
	mui('#form').on('tap','#showAgentPicker',function(e){
		agentPicker.show(function(items){
			$('#showAgentPicker').text(items[0].text);
			$('#dt').val(items[0].value);
			addPage.dt=items[0].value;
			// 返回false可以阻止选择框的关闭
			// return false;
		});
	});
	mui('#form').on('change', '#quantity', function(e){
		addPage.quantity=$('#quantity').val();
		addPage.totalScore=addPage.list.score*addPage.quantity;
	});
	var _id = $.getParameter("id");
	mui.ajax('/bonus/market/get.json', {
		data: {
			'cid': _id,
			'user.id':uid
		},
		dataType: 'json',
		success: function(data) {
			if(null!=data){
				if(null!=data.coupon) {
					if(data.coupon.infoImg!='') {
						addPage.imgs=data.coupon.infoImg.split(';');
					}
					addPage.list=data.coupon;
					addPage.totalScore=data.coupon.score;
				}
				if(null!=data.receiptEmail){
					addPage.email=data.receiptEmail;
				}
				if(null!=data.receiptName){
					addPage.recipient=data.receiptName;
				}
				if(null!=data.receiptPhone){
					addPage.phoneNumber=data.receiptPhone;
				}
				if(null!=data.receiptAddre){
					addPage.address=data.receiptAddre;
				}
			}
			var nbox = mui("#quantityBox").numbox();
			nbox.options.max=data.quantity;

			var swiper = new Swiper('.swiper-container', {
		      spaceBetween: 30,
		      centeredSlides: true,
		      autoplay: {
		        delay: 2500,
		        disableOnInteraction: false,
		      },
		      pagination: {
		        el: '.swiper-pagination',
		        clickable: true,
		      },
		      navigation: {
		        nextEl: '.swiper-button-next',
		        prevEl: '.swiper-button-prev',
		      }
		    });
		    i18nReady();
		}
	});
	var timeId = setInterval(function(){
		mui.ajax('/bonus/market/get/quantity.json', {
			data: {
				'cid': _id
			},
			type:'post',
			dataType: 'json',
			success: function(data) {
				if(null!=data&&null!=data.quantity){
					addPage.list.surplusQuantity=data.surplusQuantity;
				}
			},
			error:function(data){
				clearInterval(timeId);
			}
		});
	}, 1000);
	var agentPicker=new mui.PopPicker();
	mui.ajax('/customer/dt.json', {
		data: {
			id: uid
		},
		type: 'post',
		dataType: 'json',
		success: function(data) {
			if('1'==data.status) {
				var _dt = [],_text='';
				data.object.distributor.forEach(function(item){
					_dt.push({
						value:item.id,
						text:item.companyName
					});
					if(item.id==data.object.dt) {
						_text=item.companyName;
					}
				});
				agentPicker.setData(_dt);
				if(_text!='') {
					agentPicker.pickers[0].setSelectedValue(data.object.dt);
					$('#showAgentPicker').text(_text);
					$('#dt').val(data.object.dt);
					addPage.dt=data.object.dt;
				}
			}
		}
	});
	mui('.my-footer').on('tap','.my-btn-ok',function(){
		var _info=addPage.list;
		var _html='';
		if(_info.couponType=='0') {
			_html='<div class="_msgBox"><div>'+
					_info.couponName+'<span style="display:inline-block;width:50px;text-align:center;">*</span>'+addPage.quantity+
					'</div>'+
					'<div class="right">'+$.i18n.prop('Gift_lbl1')+addPage.totalScore+$.i18n.prop('Gift_lbl2')+'</div>'+
					'<label for="isRead"><input type="checkbox" id="isRead" value="1">'+$.i18n.prop('Gift_lbl3')+
					'</label><a id="viewIntegralAgreement" href="javascript:void(0)">'+$.i18n.prop('Gift_lbl4')+'</a>'+
					'</div>';
		}else if(_info.couponType=='1'){
			_html='<div class="_msgBox"><div>'+
					_info.couponName+'<span style="display:inline-block;width:50px;text-align:center;">*</span>'+addPage.quantity+
					'</div>'+
					'<div class="right">'+$.i18n.prop('Gift_lbl1')+addPage.totalScore+$.i18n.prop('Gift_lbl2')+'</div>'+
					'<hr/>'+
					'<div>'+$.i18n.prop('Gift_lbl6')+'<input type="text" id="recipient" name="recipient" value="'+addPage.recipient+'"></div>'+
					'<div>'+$.i18n.prop('Gift_lbl7')+'<input type="text" id="phoneNumber" name="phoneNumber" value="'+addPage.phoneNumber+'"></div>'+
					'<div>'+$.i18n.prop('Gift_lbl8')+'<textarea id="address" name="address" row="8">'+addPage.address+'</textarea></div>'+
					'<label for="isRead"><input type="checkbox" id="isRead" value="1">'+$.i18n.prop('Gift_lbl3')+
					'</label><a id="viewIntegralAgreement" href="javascript:void(0)">'+$.i18n.prop('Gift_lbl4')+'</a>'+
					'</div>';
		}else if(_info.couponType=='2'){
			_html='<div class="_msgBox"><div>'+
					_info.couponName+'<span style="display:inline-block;width:50px;text-align:center;">*</span>'+addPage.quantity+
					'</div>'+
					'<div class="right">'+$.i18n.prop('Gift_lbl1')+addPage.totalScore+$.i18n.prop('Gift_lbl2')+'</div>'+
					'<hr/>'+
					'<div>'+$.i18n.prop('Gift_lbl5')+'<input type="text" id="email" name="email" value="'+addPage.email+'"></div>'+
					'<label for="isRead"><input type="checkbox" id="isRead" value="1">'+$.i18n.prop('Gift_lbl3')+
					'</label><a id="viewIntegralAgreement" href="javascript:void(0)">'+$.i18n.prop('Gift_lbl4')+'</a>'+
					'</div>';
		}

		mui.confirm(_html,$.i18n.prop('Gift_msg1'),[$.i18n.prop('ercizhuc_No'),$.i18n.prop('ercizhuc_Yes')],function(e){
			if(e.index == 1) {
				if(!$('#isRead').is(':checked')){
					return false;
				}
				return _formSubmit();
			}
		});
		$('#viewIntegralAgreement').on('click',function(){
			viewIntegralAgreement();
		});
		$('.mui-popup-button-bold').addClass('disable');
		$('#isRead').on('click', function(){
			if($(this).is(':checked')){
				$('.mui-popup-button-bold').removeClass('disable');
			}else {
				$('.mui-popup-button-bold').addClass('disable');
			}
		});
	});
	function _formSubmit(){
		var result = false;
		switch(addPage.list.couponType){
			case '0':
				result = _formCouponSubmit();
				break;
			case '1':
			case '2':
				result = _formGiftSubmit();
				break;
			default:
				break;
		}
		return result;
	}
	function _formCouponSubmit(){
		var _param={};
		_param.score=addPage.list.score;
		_param.quantity=addPage.quantity;
		_param.value=addPage.list.value;
		_param['user.id']=uid;
		_param['user.customer.id']=uid;
		_param['regionLocation.id']=addPage.list.region.id;
		// addPage.list.countryLocation && _param['countryLocation.id']=addPage.list.countryLocation.id;
		_param['coupon.id']=addPage.list.id;
		_param['dt.id']=addPage.dt;
		_param['currency.id']=addPage.list.currency.id;
		_param.coupontype=addPage.list.couponType || '';
		_param.starttime=$.getCurrDate();
		_param.endtime=$.getDate(_param.starttime, addPage.list.validityDay);
		_param.rule=addPage.list.rule;
		if(formValid(_param)) {
			return false;
		}
		$.openLoadForm($.i18n.prop('contentRefresh'));
		mui.ajax('/customer/coupon/exchange.json', {
			data: _param,
			type: 'post',
			dataType: 'json',
			success: function(data) {
				$.closeLoadForm();
				if(data.status==1) {
					mui.alert($.i18n.prop('Coupon_message1'), "", $.i18n.prop('User_Center_ok'), function(e) {
						// var url = "../market/index.html";
						// mui.openWindow({
						// 	url: url
						// });
						mui.back();
					});
				}else if(data.status==2){
					mui.alert($.i18n.prop('Coupon_message2'));
				}else if(data.status==3){
					mui.alert($.i18n.prop('Coupon_message3'));
				}
			}
		});
	}
	function _formGiftSubmit(){
		var _param={};
		_param.integral=addPage.list.score;
		_param.quantity=addPage.quantity;
		// _param.value=addPage.list.value;
		_param['user.id']=uid;
		_param['user.customer.id']=uid;
		_param['integralGift.id']=addPage.list.id;
		if(addPage.list.couponType=='2'){
			_param['receiptEmail']=$('#email').val();
		}else if(addPage.list.couponType=='1') {
			_param['receiptName']=$('#recipient').val();
			_param['receiptPhone']=$('#phoneNumber').val();
			_param['receiptAddre']=$('#address').val();
		}
		if(formValid(_param)) {
			return false;
		}
		$.openLoadForm($.i18n.prop('contentRefresh'));
		mui.ajax('/integral/exchange/order/exchange.json', {
			data: _param,
			type: 'post',
			dataType: 'json',
			success: function(data) {
				$.closeLoadForm();
				if(data.status==1) {
					mui.alert($.i18n.prop('Coupon_message1'), "", $.i18n.prop('User_Center_ok'), function(e) {
						// var url = "../market/index.html";
						// mui.openWindow({
						// 	url: url
						// });
						mui.back();
					});
				}else if(data.status==2){
					mui.alert($.i18n.prop('Coupon_message2'));
				}else if(data.status==3){
					mui.alert($.i18n.prop('Coupon_message3'));
				}
			}
		});
	}
	function formValid(obj){
		var result = false;
		switch(addPage.list.couponType){
			case '0':
				result = _formCouponValid(obj);
				break;
			case '1':
				result = _formGiftValid1(obj);
				break;
			case '2':
				result = _formGiftValid2(obj);
				break;
			berak:
				break;
		}
		return result;
	}
	function _formCouponValid(obj){
		if(obj['dt.id']=="") {
			mui.alert($.i18n.prop('Coupon_message4'));
			return true;
		}
		return false;
	}
	function _formGiftValid1(obj){
		if(obj['receiptName']=="") {
			mui.alert($.i18n.prop('Gift_message1'));
			return true;
		}
		if(obj['receiptPhone']=="") {
			mui.alert($.i18n.prop('Gift_message2'));
			return true;
		}
		if(obj['receiptAddre']=="") {
			mui.alert($.i18n.prop('Gift_message3'));
			return true;
		}
		return false;
	}
	function _formGiftValid2(obj){
		if(obj['receiptEmail']=="") {
			mui.alert($.i18n.prop('Gift_message4'));
			return true;
		}
		return false;
	}
	function viewIntegralAgreement() {
		if(addPage.provision=='') {
			mui.ajax("/customer/integral/provision.do", {
				data: {
					"cid": addPage.uid,
					"useType":'1'
				},
				type:'post',
				success: function(data) {
					var status = data.status;
					if(status == 1) {
						addPage.provision=data.object.content;
						integralAgreement(data.object.content);
					}
				}
			});
		}else {
			integralAgreement(addPage.provision);
		}
	}
	function integralAgreement(msgStr){
		var divHeight = window.screen.availHeight-300;	
		var msg='<div style="height:'+divHeight+'px;text-align:left;position: relative;"><div class="mui-scroll-wrapper"><div class="mui-scroll">'+
		msgStr +
		'</div></div></div>';
		mui.confirm(msg, $.i18n.prop('Agree_and_Accept_Partner_Program_Terms'), [$.i18n.prop('ercizhuc_No'),$.i18n.prop('ercizhuc_Yes')], function(e) {
			if(e.index == 1) {
				// openIntegralPage();
				$('#isRead').trigger('click');
			}
		});
		mui('.mui-scroll-wrapper').scroll();
	}
});
